package com.heima.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@Order(1)
public class AdminFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //如果是登陆就直接放行
        if (request.getURI().getPath().contains("/login")) {
            return chain.filter(exchange);
        }
        //不是登陆
        //获取token
        String token = request.getHeaders().getFirst("token");
        //如果token为空，则拒绝放行
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        try {
            //判断token是否有效
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int res = AppJwtUtil.verifyToken(claims);
            if (res == 1 && res == 2) {
                //已过期
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.setComplete();
            }

            //获取用户id
            Object userId = claims.get("id");
            //添加到请求头里面
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(userId));
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            //解析失败，拒绝放行
            e.printStackTrace();
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }
}
